import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {InstanceService} from '../case.service';

import {MsgChannelService} from '../../channel/msgChannel.service';
import {TemplateService} from '../../template/template.service';
import {ResponseUtil} from '../../../../../util/response-util';
import {MsgResult} from '../../../../../models/msg-result';
import {PageSubject} from '../../../../../util/page-subject';
import {OneDialogService} from '../../../../../widgets/one-dialog/one-dialog.service';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Path} from '../../../../../portal/admin/admin-breadcrumb/breadcrumb';
import {MsgConstants} from '../../../../../constants/constants';
import {Channel} from '../../channel/channel';
import {AlarmRule, Instance} from '../instance';
import {RuleService} from '../../rule/rule.service';
import {Template} from '../../template/template';
import {DataStorageUtil} from '../../../../../util/data-storage-util';
import {isUndefined} from 'util';
import {TableUtil} from '../../../../../util/table-util';
import {MsgAPI} from '../../../msg-constants';

declare var $;
declare var moment;
declare var datepicker;

@Component({
  selector: 'app-instance-add',
  templateUrl: './instance-add.component.html'
})
export class InstanceAddComponent implements OnInit {
  submitted = false;
  //声明实例
  instances: Instance;
  receivers: Array<any> = [];
  templates: Array<Template> = [];
  // 临时存储
  type: string;
  channel: Channel;
  config;
  instanceid: string;
  instancesForm: FormGroup;
  //批量
  rules: Map<string, any> = new Map();
  ruleNames = {};

  instancesGroupForm: FormGroup;
  ids: Array<String> = [];
  table;
  groupSubmitted = false;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private pageSubject: PageSubject,
              private instanceService: InstanceService,
              private channelService: MsgChannelService,
              private templateService: TemplateService,
              private ruleService: RuleService,
              private tableUtil: TableUtil,
              private dialogService: OneDialogService,
              private responseUtil: ResponseUtil,
              private response: ResponseUtil,
              private dataStorageUtil: DataStorageUtil,
              private fb: FormBuilder) {
  }

  ngOnInit() {
    this.initObject();
    this.initTime();
    this.pushPage();
    this.initTemplate();
    this.initRule();
    this.loadInstances();
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.instances = new Instance("", "", "", "", "", "", "", "", "", "", "", "", "", "1", "", "", []);
    this.buildForm();
    this.buildGroupForm();
    if (!!this.route.snapshot.params['isGroup']) {
      this.initGroupFormData();
      this.initFormData();
    } else {
      this.initPage();
      this.addAlarmRule();
    }
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.instancesForm = this.fb.group({
      'id': [this.instances.id],
      'alarmId': [this.instances.alarmId],
      'code': [this.instances.code, [
        Validators.required
      ]],
      'alarmName': [this.instances.alarmName, [
        Validators.required
      ]],
      'template': [this.instances.template],
      'type': [{value: this.instances.type, disabled: true}],
      'sendMode': [this.instances.sendMode],
      'content': [this.instances.content],
      'level': [this.instances.level],
      'receiver': [this.instances.receiver],
      'receiverName': [this.instances.receiverName, [
        Validators.required
      ]],
      'children': [this.instances.children],
      'isReal': [this.instances.isReal],
      'startTime': [this.instances.startTime],
      'endTime': [this.instances.endTime],
      'isUse': [this.instances.isUse],

      ruleList: this.fb.array([])

    });

    this.instancesForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  private onValueChanged(data ?: any) {
    if (!this.instancesForm) {
      return;
    }
    const form = this.instancesForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      let control = form.get(field);
      let checkControls = [];
      if (!control) {
        let formArray = form.get('ruleList') as FormArray;
        if (formArray && formArray.length > 0 && formArray.controls.length > 0) {
          formArray.controls.forEach(function (formControl) {
            let fc = formControl.get(field);
            if (fc && !fc.valid) {
              checkControls.push(fc);
            }
          })

        }
      } else {
        checkControls.push(control);
      }
      checkControls.forEach(function (control) {
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            this.formErrors[field] += messages[key] + ' ';
          }
        }
      }, this);
    }
  }

  //初始化日期插件
  initTime() {
    let timeData = moment().format("YYYY-MM-DD HH:mm")
    this.config = {
      timePicker: true,
      timePickerIncrement: 1,
      singleDatePicker: true,
      timePicker24Hour: true,
      parentEl: $(".wrapper"),
      locale: {
        format: "YYYY-MM-DD HH:mm",
        separator: " 至 ",
        applyLabel: '确定',
        cancelLabel: '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1
      },
      startDate: timeData,
      endDate: timeData
    };
    $("#instance_add_startTime").daterangepicker(this.config);
    $("#instance_add_endTime").daterangepicker(this.config);
    $("#instance_add_group_startTime").daterangepicker(this.config);
    $("#instance_add_group_endTime").daterangepicker(this.config);
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("报警管理", "");
    this.pageSubject.pushPage("报警实例管理", "添加", path);
  }

  //根据通道，初始化页面数据
  initPage() {
    //获取路由参数
    let id = this.route.snapshot.params["id"];
    this.channelService.getChannelById(id).subscribe(
      result => this.responseUtil.success(result, this.processGetResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {

    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.channel = result.data;
      // console.log(JSON.stringify(result.data));
      this.instances.alarmId = this.channel.id;
      this.instances.alarmName = this.channel.alarmName;
      this.instances.sendMode = this.channel.sendMode;
      this.instances.level = this.channel.level;
      this.instances.receiver = isUndefined(this.channel.receiver) ? "" : this.channel.receiver;
      this.instances.receiverName = isUndefined(this.channel.receiverName) ? "" : this.channel.receiverName;
      this.instances.isReal = this.channel.isReal;
      this.instances.startTime = this.channel.startTime;
      this.instances.endTime = isUndefined(this.channel.endTime) ? "" : this.channel.endTime;
      this.instances.isUse = '1';
      this.instances.type = this.channel.type;
      this.type = this.channel.type;
      this.instancesForm.patchValue(this.instances);
      this.instancesGroupForm.patchValue(this.instances);
      if (this.instances.isReal == "0") {
        $("#instance_add_startTime_div").show();
        $("#instance_add_endTime_div").show();
        $("#instance_add_group_startTime_div").show();
        $("#instance_add_group_endTime_div").show();
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取所有的模板
   */

  initTemplate() {
    this.templateService.getTemplate().subscribe(
      result => this.responseUtil.success(result, this.processTemplateResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * 返回值处理
   * @param {MsgResult} result
   */

  private processTemplateResult = (result: MsgResult) => {

    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //console.log(result);
      this.templates = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取所有的规则
   */

  initRule() {
    this.ruleService.getRule().subscribe(
      result => this.responseUtil.success(result, this.processRuleResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * 返回值处理
   * @param {MsgResult} result
   */

  private processRuleResult = (result: MsgResult) => {
    // console.log("rules"+result);
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      // this.rules = result.data;
      if (result.data) {
        result.data.forEach(function (rule) {
          let ruleName = rule.ruleName;
          let ruleOpers = rule.operation;
          let ruleValues = rule.value;
          let operArr = ruleOpers.split(",");
          let valueArr = ruleValues.split(",")
          this.rules.set(ruleName, {ruleOpers: operArr, ruleVals: valueArr});
        }, this);
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 接收发送人数据后重新赋值
   */
  initFormData() {
    let isGroup = this.route.snapshot.params['isGroup'];
    // console.log(isGroup);
    if ('0' == isGroup) {
      $("#singleli").addClass("active").siblings("#groupli").removeClass("active");
      $("#tab_1").addClass("active").siblings("#tab_2").removeClass("active");
    }
    this.instances = this.instancesForm.value;
    // console.log(this.instances);
    this.instances.code = this.dataStorageUtil.get("code");
    this.instances.alarmName = this.dataStorageUtil.get("alarmName");
    this.type = this.dataStorageUtil.get("type");
    this.instances.type = this.dataStorageUtil.get("type");
    this.instances.sendMode = this.dataStorageUtil.get("sendMode");
    this.instances.level = this.dataStorageUtil.get("level");

    if (!!this.route.snapshot.params['tag']) {
      this.receivers = JSON.parse(this.dataStorageUtil.get("receiver"));
      let receiverName = "";
      let receiver = "";
      this.receivers.forEach((value) => {
        receiverName += value.name + ",";
        receiver += value.id + "|" + value.type + ",";
      });

      this.instances.receiver = receiver;
      this.instances.receiverName = receiverName;
    } else {
      this.instances.receiver = this.dataStorageUtil.get("receiver");
      this.instances.receiverName = this.dataStorageUtil.get("receiverName");
    }

    this.instances.isReal = this.dataStorageUtil.get("isReal");
    this.instances.content = this.dataStorageUtil.get("content");
    this.instances.template = this.dataStorageUtil.get("template");
    this.instances.alarmId = this.dataStorageUtil.get("alarmId");
    this.instances.startTime = this.dataStorageUtil.get("startTime");
    this.instances.endTime = this.dataStorageUtil.get("endTime");
    this.instances.isUse = this.dataStorageUtil.get("isUse");

    this.instances.alarmRules = JSON.parse(this.dataStorageUtil.get("alarmRules"));
    this.setMapPoints(this.instances.alarmRules);
    this.instancesForm.patchValue(this.instances);
    if ('0' == this.instances.isReal) {
      $("#instance_add_startTime_div").show();
      $("#instance_add_endTime_div").show();
    }
    this.instances.alarmRules.forEach(function (value, index, array) {
      this.pushRule(index, value.ruleName);
    }, this)

  }

  get ruleList(): FormArray {
    return this.instancesForm.get('ruleList') as FormArray;
  }

  addAlarmRule() {
    this.ruleList.push(this.fb.group({
      alarmId: '',
      orderNumber: ['', [Validators.required, Validators.pattern("^[0-9]*[1-9][0-9]*$")]],
      ruleName: ['', Validators.required],
      ruleOperation: ['', Validators.required],
      ruleValue: ['', Validators.required],
      successNext: ['', [Validators.pattern("^[0-9]*[1-9][0-9]*$")]],
      failNext: ['', [Validators.pattern("^[0-9]*[1-9][0-9]*$")]],
      isUse: '1'
    }));
  }

  setMapPoints(alarmRule: AlarmRule[]) {
    const alarmRuleFGs = alarmRule.map(alarmRule => this.fb.group(alarmRule));
    const alarmRuleFormArray = this.fb.array(alarmRuleFGs);
    this.instancesForm.setControl('ruleList', alarmRuleFormArray);
  }

  ngOnChanges() {
    this.instancesForm.reset();
    this.setMapPoints(this.instances.alarmRules);

  }

  prepareSaveAlarmRule(): Instance {
    const formModel = this.instancesForm.value;
    // deep copy of form model lairs
    const ruleListDeepCopy: AlarmRule[] = formModel.ruleList.map(
      (alarmRule: AlarmRule) => Object.assign({}, alarmRule)
    );
    // return new `Hero` object containing a combination of original hero value(s)
    // and deep copies of changed form model values
    const instance: Instance = {
      id: this.instances.id,
      alarmId: this.instances.alarmId,
      code: formModel.code,
      alarmName: formModel.alarmName,
      type: this.instances.type,
      content: formModel.content,
      sendMode: formModel.sendMode,
      level: formModel.level,
      receiver: formModel.receiver,
      receiverName: formModel.receiverName,
      children: formModel.children,
      isReal: formModel.isReal,
      startTime: formModel.startTime,
      endTime: formModel.endTime,
      isUse: formModel.isUse,
      template: this.instances.template,
      alarmRules: ruleListDeepCopy
    };
    return instance;
  }


  remove(i) {
    //删除一行
    this.ruleList.controls.splice(i, 1);
    this.ruleList.removeAt(i);
  }

  //添加实例
  onSubmit() {
    this.instances = this.prepareSaveAlarmRule();
    this.instances.startTime = $("#instance_add_startTime").val();
    this.instances.endTime = $("#instance_add_endTime").val();
    this.instances.type = this.type;
    // console.log(JSON.stringify(this.instances));
    this.submitted = true;
    this.instanceService.addInstance(this.instances, '0').subscribe(
      result => this.responseUtil.success(result, this.processResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取返回信息
   * @param json
   */
  private processResult = (result: MsgResult) => {

    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      // console.log(result);
      this.instanceid = result.data.id;
      this.dialogService.success("添加成功", () => this.cancelInstanceAdd(), () => this.cancelInstanceAdd());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.submitted = false;
      this.dialogService.info(result.message);
    }
  }

  /**
   * 添加页面跳转
   */
  cancelInstanceAdd() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'alarmName': '',
    'code': '',
    'receiverName': '',
    'ruleName': '',
    'ruleOperation': '',
    'ruleValue': '',
    'orderNumber': '',
    'successNext': '',
    'failNext': '',
  };
  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'alarmName': {
      'required': '名称不能为空'
    },
    'code': {
      'required': '编码不能为空'
    },
    'receiverName': {
      'required': '接收人不能为空'
    },
    'ruleName': {
      'required': '请选择规则'
    },
    'ruleOperation': {
      'required': '请选择操作'
    },
    'ruleValue': {
      'required': '请设置阈值'
    },
    'orderNumber': {
      'required': '请输入执行序号',
      'pattern': '执行序号必须为整数'
    },
    'successNext': {
      'pattern': '请填写其他规则的执行序号，或默认空'
    },
    'failNext': {
      'pattern': '请填写其他规则的执行序号，或默认空'
    }
  };

  //将选中模板的note放入content中
  pushTemplateId(note) {
    this.instances.content = note;
    this.instances.template = note;
  }

  //将所选规则放入ruleName;
  pushRule(i, ruleName) {

    this.ruleNames[i] = ruleName;

  }

  //所有规则名
  getRuleNames(): Array<any> {
    let ruleNames = [];

    let its = this.rules.forEach(function (v, k, map) {
      ruleNames.push(k);

    });

    return ruleNames;
  }

  //根据第几个，获得相应的运算
  getRuleOpers(i): Array<any> {
    let ruleName = this.ruleNames[i];
    return this.rules.get(ruleName) ? this.rules.get(ruleName).ruleOpers : [];
  }

  //根据第几个，获得相应的值
  getRuleVals(i): Array<any> {
    let ruleName = this.ruleNames[i];
    return this.rules.get(ruleName) ? this.rules.get(ruleName).ruleVals : [];
  }

  //定时发送、时间控件显示
  noClickFun(e) {
    $("#instance_add_startTime_div").show();
    $("#instance_add_endTime_div").show();

  }

  //实时发送、时间控件隐藏
  yesClickFun(e) {
    $("#instance_add_startTime_div").hide();
    $("#instance_add_endTime_div").hide();
    $("#instance_add_startTime").val("");
    $("#instance_add_endTime").val("");
  }

  //跳转发送人页面
  getReceiver() {
    this.instances = this.prepareSaveAlarmRule();
    this.dataStorageUtil.set("alarmName", this.instances.alarmName);
    this.dataStorageUtil.set("code", this.instances.code);
    this.dataStorageUtil.set("type", this.type);
    this.dataStorageUtil.set("sendMode", this.instances.sendMode);
    this.dataStorageUtil.set("level", this.instances.level);
    this.dataStorageUtil.set("isReal", this.instances.isReal);
    this.dataStorageUtil.set("content", this.instances.content);
    this.dataStorageUtil.set("template", this.instances.template);
    this.dataStorageUtil.set("alarmId", this.instances.alarmId);

    this.dataStorageUtil.set("startTime", $("#instance_add_startTime").val());
    this.dataStorageUtil.set("endTime", $("#instance_add_endTime").val());
    this.dataStorageUtil.set("isUse", this.instances.isUse);

    this.dataStorageUtil.set("alarmRules", JSON.stringify(this.instances.alarmRules));

    this.dataStorageUtil.set("receiver", this.instances.receiver);
    this.dataStorageUtil.set("receiverName", this.instances.receiverName);

    this.router.navigate(['../assign-receiver', {
      initReceiver: this.instances.receiver, isGroup: '0'
    }], {relativeTo: this.route});
  }

  //上一步的操作
  goCategory() {
    this.router.navigate(['../category'], {relativeTo: this.route});
  }

  /****************************************************************************/
  /********************************第二表单处理*********************************/
  /****************************************************************************/

  /**
   * 构造表单
   */
  buildGroupForm(): void {
    this.instancesGroupForm = this.fb.group({
      'id': [this.instances.id],
      'alarmId': [this.instances.alarmId],
      'code': [this.instances.code, [
        Validators.required
      ]],
      'alarmName': [this.instances.alarmName, [
        Validators.required
      ]],
      'template': [this.instances.template],
      'type': [{value: this.instances.type, disabled: true}],
      'sendMode': [this.instances.sendMode],
      'content': [this.instances.content],
      'level': [this.instances.level],
      'receiver': [this.instances.receiver],
      'receiverName': [this.instances.receiverName, [
        Validators.required
      ]],
      'children': [this.instances.children],
      'isReal': [this.instances.isReal],
      'startTime': [this.instances.startTime],
      'endTime': [this.instances.endTime],
      'isUse': [this.instances.isUse],

    });

    this.instancesGroupForm.valueChanges.subscribe(
      data => this.onGroupValueChanged(data)
    );
    this.onGroupValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onGroupValueChanged(data?: any) {
    if (!this.instancesGroupForm) {
      return;
    }
    const form = this.instancesGroupForm;
    for (const field in this.groupFormErrors) {
      this.groupFormErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.groupValidationMessages[field];
        for (const key in control.errors) {
          this.groupFormErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  //添加实例
  onGroupSubmit() {
    this.instances = this.instancesGroupForm.value;
    this.instances.startTime = $("#instance_add_group_startTime").val();
    this.instances.endTime = $("#instance_add_group_endTime").val();
    this.instances.type = this.type;
    let rows = this.table.bootstrapTable('getSelections');
    let ids = this.tableUtil.getCloumns(rows, "id");
    this.instances.children = ids.join(',');

    this.groupSubmitted = true;
    this.instanceService.addInstance(this.instances, '1').subscribe(
      result => this.responseUtil.success(result, this.processGroupResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取返回信息
   * @param json
   */
  private processGroupResult = (result: MsgResult) => {

    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      // console.log(result);
      this.instanceid = result.data.id;
      this.dialogService.success("添加成功", () => this.cancelInstanceAdd(), () => this.cancelInstanceAdd());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.submitted = false;
      this.dialogService.info(result.message);
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  groupFormErrors = {
    'alarmName': '',
    'code': '',
    'receiverName': '',
    'ruleName': '',
    'ruleOperation': '',
    'ruleValue': '',
    'orderNumber': '',
    'successNext': '',
    'failNext': '',
  };
  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  groupValidationMessages = {
    'alarmName': {
      'required': '名称不能为空'
    },
    'code': {
      'required': '编码不能为空'
    },
    'receiverName': {
      'required': '接收人不能为空'
    },
    'ruleName': {
      'required': '请选择规则'
    },
    'ruleOperation': {
      'required': '请选择操作'
    },
    'ruleValue': {
      'required': '请设置阈值'
    },
    'orderNumber': {
      'required': '请输入执行序号',
      'pattern': '执行序号必须为整数'
    },
    'successNext': {
      'pattern': '请填写其他规则的执行序号，或默认空'
    },
    'failNext': {
      'pattern': '请填写其他规则的执行序号，或默认空'
    }
  };

  search() {
    this.table.bootstrapTable('refresh');
  }

  loadInstances() {
    this.table = this.tableUtil.load("one_table_instances", {
      columns: [
        {checkbox: true, width: 25, formatter: this.stateFormatter},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "alarmName", title: '报警实例名', align: 'left', switchable: false},
        {field: "code", title: '实例编码', align: 'left', switchable: false},
        {field: "type", title: '类型', align: 'left', formatter: this.typeFormat},
        {field: "sendMode", title: '发送方式', align: 'left', formatter: this.sendModeFormat},
        {field: "level", title: '发送级别', align: 'left', formatter: this.levelFormat},
        {field: "receiverName", title: '发送对象', align: 'left', formatter: this.stringFormat},
        {field: "isReal", title: '是否实时', align: 'left', formatter: this.yesOrNoFormat, visible: false},
        {field: "startTime", title: '开始时间', align: 'left', width: '100', visible: false},
        {field: "endTime", title: '结束时间', align: 'left', width: '100', visible: false},
        {field: "isUse", title: '有效', align: 'left', formatter: this.yesOrNoFormat},
      ],
      idField: "id",
      sidePagination: 'server',
      undefinedText: '-',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_instance",
      url: MsgAPI.instancesPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.isGroup = '0';
        params.alarmName = $("#instanceGroupName").val();
        params.code = $("#instanceGroupCode").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.response.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.create_date = value.createDate || '';
            value.update_date = value.updateDate || '';
          });
        });
      },
      height: 500,//table高度
      sortable: true,
      sortOrder: 'desc',
      sortName: 'CREATE_DATE',
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
  }

  //复选框进行判断；
  private stateFormatter = (value, row, index) => {
    let result;
    this.ids.forEach((id) => {
      if (row.id == id) {
        result = {
          disabled: false,//设置是否可用
          checked: true//设置选中
        };
        return;
      }
    });
    return result;
  }

  /**
   * 字符超过40后，只显示40个字
   * @param value
   * @param row
   * @param index
   * @returns {string}
   */

  private stringFormat(value, row, index) {

    if (!value) {
      return '-';
    }

    return '<span style="display: inline-block;width: 180px;" title="' + value + '">' + value + '</span>'
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }

  /**
   * 发送方式判断
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */

  private sendModeFormat(value, row, index) {
    if (value == '1') {
      return '应用内';
    }
    if (value == '2') {
      return '短信';
    }
    if (value == '3') {
      return '邮件';
    }
  }

  /**
   * 报警级别判断
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */

  private levelFormat(value, row, index) {
    switch (value){
      case '1':
        return '蓝色';
      case '2':
        return '黄色';
      case '3':
        return '橙色';
      case '4':
        return '红色';
      default:
        return '-';
    }
  }

  /**
   * 报警类型判断
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */

  private typeFormat(value, row, index) {
    if (value == '1') {
      return '标准站';
    }
    if (value == '2') {
      return '微型站';
    }
    if (value == '3') {
      return '工业废气';
    }
    if (value == '4') {
      return '扬尘';
    }
    if (value == '5') {
      return '油烟';
    }
    if (value == '6') {
      return '油漆房';
    }
    if (value == '7') {
      return '加油站';
    }
    if (value == '8') {
      return '工业废水';
    }
    if (value == '9') {
      return '水质断层';
    }
    return '其他';

  }

  //定时发送、时间控件显示
  noGroupClickFun(e) {
    $("#instance_add_group_startTime_div").show();
    $("#instance_add_group_endTime_div").show();

  }

  //实时发送、时间控件隐藏
  yesGroupClickFun(e) {
    $("#instance_add_group_startTime_div").hide();
    $("#instance_add_group_endTime_div").hide();
    $("#instance_add_group_startTime").val("");
    $("#instance_add_group_endTime").val("");
  }

//跳转发送人页面
  getGroupReceiver() {
    this.instances = this.instancesGroupForm.value;

    let rows = this.table.bootstrapTable('getSelections');
    let ids = this.tableUtil.getCloumns(rows, "id");
    this.instances.children = ids.join(',');

    this.dataStorageUtil.set("alarmName", this.instances.alarmName);
    this.dataStorageUtil.set("code", this.instances.code);
    this.dataStorageUtil.set("type", this.type);
    this.dataStorageUtil.set("sendMode", this.instances.sendMode);
    this.dataStorageUtil.set("level", this.instances.level);
    this.dataStorageUtil.set("isReal", this.instances.isReal);
    this.dataStorageUtil.set("content", this.instances.content);
    this.dataStorageUtil.set("template", this.instances.template);
    this.dataStorageUtil.set("alarmId", this.instances.alarmId);
    this.dataStorageUtil.set("children", this.instances.children);

    this.dataStorageUtil.set("startTime", $("#instance_add_group_startTime").val());
    this.dataStorageUtil.set("endTime", $("#instance_add_group_endTime").val());
    this.dataStorageUtil.set("isUse", this.instances.isUse);

    this.dataStorageUtil.set("receiver", this.instances.receiver);
    this.dataStorageUtil.set("receiverName", this.instances.receiverName);

    this.router.navigate(['../assign-receiver', {
      initReceiver: this.instances.receiver, isGroup: '1'
    }], {relativeTo: this.route});
  }

  /**
   * 接收发送人数据后重新赋值
   */
  initGroupFormData() {
    this.instances = this.instancesGroupForm.value;
    // console.log(this.instances);
    this.instances.code = this.dataStorageUtil.get("code");
    this.instances.alarmName = this.dataStorageUtil.get("alarmName");
    this.type = this.dataStorageUtil.get("type");
    this.instances.type = this.dataStorageUtil.get("type");
    this.instances.sendMode = this.dataStorageUtil.get("sendMode");
    this.instances.level = this.dataStorageUtil.get("level");
    let isGroup = this.route.snapshot.params['isGroup'];
    if ('1' == isGroup) {
      $("#singleli").removeClass("active").siblings("#groupli").addClass("active");
      $("#tab_1").removeClass("active").siblings("#tab_2").addClass("active");
    }

    if (!!this.route.snapshot.params['tag']) {
      this.receivers = JSON.parse(this.dataStorageUtil.get("receiver"));
      let receiverName = "";
      let receiver = "";
      this.receivers.forEach((value) => {
        receiverName += value.name + ",";
        receiver += value.id + "|" + value.type + ",";
      });

      this.instances.receiver = receiver;
      this.instances.receiverName = receiverName;
    } else {
      this.instances.receiver = this.dataStorageUtil.get("receiver");
      this.instances.receiverName = this.dataStorageUtil.get("receiverName");
    }
    this.instances.isReal = this.dataStorageUtil.get("isReal");
    this.instances.content = this.dataStorageUtil.get("content");
    this.instances.template = this.dataStorageUtil.get("template");
    this.instances.alarmId = this.dataStorageUtil.get("alarmId");
    this.instances.startTime = this.dataStorageUtil.get("startTime");
    this.instances.endTime = this.dataStorageUtil.get("endTime");
    this.instances.isUse = this.dataStorageUtil.get("isUse");

    this.instances.children = this.dataStorageUtil.get("children");

    this.instancesGroupForm.patchValue(this.instances);
    if (this.instances.isReal == "0") {
      $("#instance_add_group_startTime_div").show();
      $("#instance_add_group_endTime_div").show();
    }

    if (!!this.instances.children) {
      let idStrs = this.instances.children.split(",");
      idStrs.forEach((value) => {
        this.ids.push(value);
      });
    }
  }


}
